package com.sansui.blog.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sansui.blog.dao.BlogDao;
import com.sansui.blog.dao.TagDao;
import com.sansui.blog.dao.TypeDao;
import com.sansui.blog.pojo.Blog;
import com.sansui.blog.pojo.Tag;
import com.sansui.blog.pojo.Type;
import com.sansui.blog.pojo.vo.BlogInfoQuery;
import com.sansui.blog.pojo.vo.BlogQuery;
import com.sansui.blog.service.BlogService;
import com.sansui.blog.utils.MarkdownUtils;
import com.sansui.blog.utils.NewsSummary;
import com.sansui.blog.utils.StrSpilt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @name: BlogServiceImpl
 * @author: Sansui
 * @Software: IDEA
 * @Blog: https://www.cnblogs.com/sansui6/
 * @date: 2022-04-03 00:51
 **/
@Service
public class BlogServiceImpl implements BlogService {


    @Autowired
    private BlogDao blogDao;
    @Autowired
    private TypeDao typeDao;
    @Autowired
    private TagDao tagDao;

    @Override
    public Map<String, Object> countBlogInfo() {
        return blogDao.countBlogInfo();
    }

    @Override
    public Map<String, Object> getAllBlogByPage(Integer page, Integer limit){
        Map<String,Object> data = new HashMap<>(16);
        try {
            Integer pages = (page-1)*limit;
            List<Blog> blogs = blogDao.getAllBlogByPage(pages, limit);
            Integer blogCount = blogDao.countBlog();
            data.put("code",0);
            data.put("msg","查询成功！");
            data.put("count",blogCount);
            data.put("data",blogs);
        }catch (Exception e){
            data.put("code",400);
            data.put("msg","查询失败！");
        }
        return data;
    }

    @Transactional
    @Override
    public Map<String, Object> updateStatus(Long blogId, String status) {
        Map<String,Object> data = new HashMap<>(16);
        Blog blog = blogDao.getBlogById(blogId);
        if (blog==null){
            data.put("code",500);
            data.put("msg","修改失败，文章不存在！");
            return data;
        }

        Integer updateBlogStatus = blogDao.updateStatus(blogId , status);
        if (updateBlogStatus != 1){
            data.put("code",400);
            data.put("msg","修改失败！");
            return data;
        }

        data.put("code",200);
        data.put("msg","修改成功！");
        return data;
    }

    @Transactional
    @Override
    public Map<String, Object> addBlog(Blog blog , String username){
        Map<String,Object> data = new HashMap<>(16);
        NewsSummary summary=new NewsSummary();

        try {

            String[] typeIds = blog.getTypesId().split(",");
            for (String str : typeIds) {
                Type type = typeDao.getTypeById(Long.valueOf(str));
                if (type == null) {
                    data.put("code", 401);
                    data.put("msg", "保存失败，包含不存在的分类！");
                    return data;
                }
            };

            String[] tIds = blog.getTagsId().split(",");
            for (String str : tIds) {
                Tag tag = tagDao.getTagById(Long.valueOf(str));
                if (tag == null) {
                    data.put("code", 402);
                    data.put("msg", "保存失败,包含不存在的标签！");
                    return data;
                }
            };

            String keySentences = summary.SummaryMeanstdTxt(blog.getContent());
            blog.setDescription(keySentences);
            blog.setCreateTime(new Date());
            blog.setCreateUser(username);
            blog.setUpdateTime(new Date());
            blog.setUpdateUser(username);
            blogDao.addBlog(blog);
            data.put("code",200);
            data.put("msg","添加成功！");
        }catch (Exception e){
            e.printStackTrace();
            data.put("code",400);
            data.put("msg","文章添加失败！");
        }
        return data;
    }

    @Transactional
    @Override
    public Map<String, Object> updateBlog(Blog blog, String username) {
        Map<String,Object> data = new HashMap<>(16);
        try {
            String[] typeIds = blog.getTypesId().split(",");
            for (String str : typeIds) {
                Type type = typeDao.getTypeById(Long.valueOf(str));
                if (type == null) {
                    data.put("code", 401);
                    data.put("msg", "保存失败，包含不存在的分类！");
                    return data;
                }
            };

            String[] tIds = blog.getTagsId().split(",");
            for (String str : tIds) {
                Tag tag = tagDao.getTagById(Long.valueOf(str));
                if (tag == null) {
                    data.put("code", 402);
                    data.put("msg", "保存失败,包含不存在的标签！");
                    return data;
                }
            };

            blog.setUpdateTime(new Date());
            blog.setUpdateUser(username);
            blogDao.updateBlog(blog);
            data.put("code",200);
            data.put("msg","保存成功！");
        }catch (Exception e){
            e.printStackTrace();
            data.put("code",400);
            data.put("msg","文章保存失败！");
        }
        return data;
    }

    @Transactional
    @Override
    public Map<String, Object> deleteBlog(Long blogId) {
        Map<String,Object> data = new HashMap<>(16);
        try{
            Blog blog = blogDao.getBlogById(blogId);
            if(blog == null){
                data.put("code",401);
                data.put("msg","删除失败！文章不存在");
                return data;
            }
            Integer delNum = blogDao.deleteBlog(blogId);
            if(delNum != 1){
                data.put("code",402);
                data.put("msg","文章删除失败！");
                return data;
            }
            data.put("code",200);
            data.put("msg","删除成功！");
        }catch (Exception e){
//            e.printStackTrace();
            data.put("code",400);
            data.put("msg","删除失败！");
        }
        return data;
    }

    /**
     * 批量删除博客信息
     * @return 批量删除博客信息
     */
    @Transactional
    @Override
    public Map<String, Object> deleteBlogByIds(List<String> delList) {
        Map<String,Object> data = new HashMap<>(16);
        try{
            blogDao.deleteBlogByIds(delList);
            data.put("code",200);
            data.put("msg","批量删除成功！");
        }catch (Exception e){
            data.put("code",400);
            data.put("msg","批量删除失败！");
        }
        return data;
    }

    /**
     * 查询博客信息
     * @return 查询博客信息
     */
    @Override
    public Map<String, Object> blogQuery(BlogQuery blog) {
        Map<String,Object> data = new HashMap<>(16);
        try{
            List<Blog> blogs = blogDao.blogQuery(blog);
            data.put("code",0);
            data.put("msg","查询成功！");
            data.put("count",blogs.size());
            data.put("data",blogs);

        }catch (Exception e){
            e.printStackTrace();
            data.put("code",400);
            data.put("msg","查询失败！");
        }
        return data;
    }

    ///////////////////////////////////

    @Override
    public PageInfo<BlogInfoQuery> queryAllByPage(Integer pageNum, Integer pageSize,Long typeId ,Long tagId,String keyword) {

        if(pageNum < 1){
            pageNum = 1;
        }
        Integer page = (pageNum-1)*pageSize;
        List <BlogInfoQuery> blogs = blogDao.queryAllByPage(page,pageSize,typeId,tagId,keyword);

        PageInfo <BlogInfoQuery> pageInfo = new PageInfo<>(blogs);

        Long total = Long.valueOf(0);
        if(keyword == null && typeId == null && tagId == null){
            total = Long.valueOf(String.valueOf(blogDao.countBlogInfo().get("countblog")));
        }else{
            if(keyword != null){
                total = blogDao.queryAllCount(null,null,keyword);
            }else{
                total = blogDao.queryAllCount(typeId,tagId,null);
            }
        }
//       当前页 pageNum=1,每页数量 pageSize=5, size=3, startRow=0, endRow=2, 总数 total=3, 总页数 pages=1,

        // 总数
        pageInfo.setTotal(total);
        // 当前页
        pageInfo.setPageNum(pageNum);
        // 每页数量 pageSize
        pageInfo.setPageSize(pageSize);
        // 总页数 pages
        int pages = (int)Math.ceil((double)total/pageSize);
        pageInfo.setPages(pages);
        // 是否第一页 setIsFirstPage
        pageInfo.setIsFirstPage((page == 0)?true:false);
        // 是否最后一页 isLastPage
        pageInfo.setIsLastPage((pageNum == pages)?true:false);
        // 是否有前一页 hasPreviousPage
        pageInfo.setHasPreviousPage((pageNum > 1)?true:false);
        // 是否有下一页 hasNextPage
        int pagesNum = (int)Math.ceil((double)pages/pageNum);
        pageInfo.setHasNextPage((pagesNum > 1)?true:false);

        // 前一页 prePage
        pageInfo.setPrePage(pageNum-1);
        // 下一页 nextPage
        pageInfo.setNextPage(pageNum+1);
        return pageInfo;
    }

    @Override
    public Long countTNum(Long typeId , Long tagId){
        Long countTNum = Long.valueOf(0);

        if(typeId != null){
            countTNum = Long.valueOf(typeDao.countTypeNum());
        }

        if(tagId != null){
            countTNum = Long.valueOf(tagDao.countTagNum());
        }
        return countTNum;
    }

    @Override
    public List<Blog> getRecommendedBlog(){
        return blogDao.getRecommendedBlog();
    }

    /**
     * 根据id获取博客信息
     * @param blogId
     * @return
     */
    @Override
    public Blog getBlogById(Long blogId){
        return blogDao.getBlogById(blogId);
    }

    /**
     * 更新博客访问量
     * @param blogId
     * @return
     */
    @Transactional
    @Override
    public Integer updateBlogViews(Long blogId){
        return blogDao.updateBlogViews(blogId);
    }



    @Override
    public Blog getAndConvert(Long blogId){
        Blog blog = blogDao.getBlogById(blogId);
        if(blog == null){
            return null;
        }
        Blog b = new Blog();
        BeanUtils.copyProperties(blog,b);
        String content = b.getContent();
        b.setContent(MarkdownUtils.markdownToHtmlExtensions(content));
        return b;
    }

    /**
     * 根据id获取文章对应标签信息
     * @param blogId
     * @return
     */
    @Override
    public List<Map<String, Object>> getBlogIsTagsInfo(Long blogId) {
        return blogDao.getBlogIsTagsInfo(blogId);
    }

    /**
     * 根据博客id获取博客上下分页数据
     * @param blogId
     * @return
     */
    @Override
    public Map<String, Object> getBogPageChange(Long blogId) {
        Map<String,Object> data = new HashMap<>(16);
        //上一页数据
        List<BlogInfoQuery> perBlog = blogDao.getBogPageChange(blogId,"0");
        //下一页数据
        List<BlogInfoQuery> nextBlog = blogDao.getBogPageChange(blogId,null);
        data.put("perBlog",perBlog);
        data.put("nextBlog",nextBlog);
        return data;
    }

}
